package com.lhy.admin.web;

import com.lhy.admin.common.secure.authentication.Authentication;
import com.lhy.admin.common.secure.authorization.Permissions;
import com.lhy.admin.model.User;
import com.lhy.admin.service.UserService;
import com.lhy.admin.util.AuthUtil;
import com.lhy.admin.util.StringUtil;
import com.lhy.commonweb.model.Page;
import com.lhy.commonweb.model.RequestPage;
import com.lhy.commonweb.model.ResponseResult;
import com.lhy.commonweb.service.AbstractService;
import com.lhy.commonweb.web.BaseControllerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
@Permissions
public class UserController extends BaseControllerImpl<User, Integer> {

    @Autowired
    AuthUtil authUtil;

    public UserController(@Qualifier("userService") AbstractService service) {
        super(service);
    }

    @Override
    @Permissions("user.view")
    public Page<User> query(@Validated @ModelAttribute RequestPage requestPage, @Validated @ModelAttribute User bean) {
        return UserService.class.cast(service).query(requestPage.getPage(), requestPage.getRows(), requestPage.getSc(), bean);
    }

    @Override
    @Permissions("user.view")
    public User get(@PathVariable("id") Integer id) {
        return super.get(id);
    }

    @Override
    @Permissions("user.add")
    public ResponseResult create(@RequestBody User bean) {
        if (StringUtils.hasText(bean.getPass())) {
            String md5Pass = StringUtil.md5(bean.getPass(), bean.getName());
            bean.setPass(md5Pass);
        }
        return super.create(bean);
    }

    @Override
    @Permissions("user.edit")
    public ResponseResult update(@RequestBody User bean) {
        if (StringUtils.hasText(bean.getPass())) {
            String md5Pass = StringUtil.md5(bean.getPass(), bean.getName());
            bean.setPass(md5Pass);
        }
        return super.update(bean);
    }

    @Override
    @Permissions("user.del")
    public ResponseResult delete(@PathVariable("id") Integer id) {
        return super.delete(id);
    }

    @Authentication
    @RequestMapping(value = "avatar",method = RequestMethod.PUT)
    public ResponseResult avatar(@RequestBody User bean){
        return super.update(new User().setId(authUtil.getUser().getId()).setAvatar(bean.getAvatar()));
    }
}
